package com.dawnling.androidutils.typeface;

import android.graphics.Typeface;
import android.util.Log;

import androidx.collection.SimpleArrayMap;

import com.dawnling.androidutils.app.MyApplicaition;

import java.io.File;

/**
 * Description:util for cache typeface
 */
public class TypefaceUtil {
    private static final String TAG = "TypefaceUtil";
    private static final String FONT_DIR = "/storage/emulated/0/fonts/";
    private static final String DEFAULT_FONT = "microsoftyahei.ttf";
    private static final SimpleArrayMap<String, Typeface> TYPEFACE_CACHE = new SimpleArrayMap<String, Typeface>();

    //根据服务器返回字体名字获取字体
    public static Typeface getByPath(String path) {
        if (DEFAULT_FONT.equals(path)) {
            return get(DEFAULT_FONT);//默认字体
        }
        synchronized (TYPEFACE_CACHE) {
            if (!TYPEFACE_CACHE.containsKey(path)) {
                try {
                    //todo 服务器返回的字体如果是其他格式
                    Typeface t = Typeface.createFromFile(path);
                    TYPEFACE_CACHE.put(path, t);
                } catch (Exception e) {
                    Log.e(TAG, "Could not get typeface '" + path
                            + "' because " + e.getMessage());
                    return null;
                }
            }
            return TYPEFACE_CACHE.get(path);
        }
    }

    //根据asset中文件名获取字体
    public static Typeface get(String name) {
        synchronized (TYPEFACE_CACHE) {
            if (!TYPEFACE_CACHE.containsKey(name)) {

                try {
                    Typeface t = Typeface.createFromAsset(MyApplicaition.getApp().getAssets(), name);
                    TYPEFACE_CACHE.put(name, t);
                } catch (Exception e) {
                    Log.e(TAG, "Could not get typeface '" + name
                            + "' because " + e.getMessage());
                    return null;
                }
            }
            return TYPEFACE_CACHE.get(name);
        }
    }

    //获取字体路径
    public static String getFontPath(FontEntity fontEntity) {
        if (fontEntity == null) {
            throw new RuntimeException("选择字体失败");
        }
        if (fontEntity.getTypeface().equals(DEFAULT_FONT)) {
            return DEFAULT_FONT;
        }

        String url = fontEntity.getDownload_url();//xxx.ttf.zip
        String[] s = url.split("\\.");
        if (s.length < 3) {
            throw new RuntimeException("选择字体失败");
        }
        String suffix = s[s.length - 2];
        String typeface = fontEntity.getTypeface().toLowerCase();
        String fontPath = FONT_DIR + typeface + "." + suffix;//font的本地路径
        return fontPath;
    }

    public static boolean isFontExists(String fontPath) {
        return DEFAULT_FONT.equals(fontPath) || new File(fontPath).exists();
    }
}
